package org.catspaw.cherubim.security.ss3.rbac;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.catspaw.cherubim.security.SecurityManager;
import org.catspaw.cherubim.security.rbac.Permission;
import org.catspaw.cherubim.security.rbac.Role;
import org.catspaw.cherubim.security.rbac.dao.PermissionDao;
import org.catspaw.cherubim.security.rbac.dao.RoleDao;
import org.catspaw.cherubim.security.ss3.SpringSecuritySubject;
import org.catspaw.cherubim.security.ss3.SpringSecuritySubjectManager;

public class RoleBasedSpringSecuritySecurityManager extends
		SpringSecuritySubjectManager implements SecurityManager {

	private RoleDao			roleDao;
	private PermissionDao	permissionDao;

	public boolean checkPermission(String resourceCode, String operationCode) {
		SpringSecuritySubject subject = (SpringSecuritySubject) getCurrentSubject();
		Set<String> authorities = subject.getAuthorityCodes();
		Collection<Role> roles = new HashSet<Role>();
		if (operationCode != null) {
			Permission permission = permissionDao
					.findByDomainCodeAndActionCode(resourceCode,
														operationCode);
			List<? extends Role> list = roleDao.findByPermissionCode(permission
					.getCode());
			roles.addAll(list);
		} else {
			List<? extends Permission> permissions = permissionDao
					.findByDomainCode(resourceCode);
			for (Permission permission : permissions) {
				List<? extends Role> list = roleDao
						.findByPermissionCode(permission.getCode());
				roles.addAll(list);
			}
		}
		for (Role role : roles) {
			if (authorities.contains(role.getCode())) {
				return true;
			}
		}
		return false;
	}

	public boolean hasRole(String roleCode) {
		SpringSecuritySubject subject = (SpringSecuritySubject) getCurrentSubject();
		List<? extends Role> roles = roleDao.findByUsername(subject
				.getUsername());
		for (Role role : roles) {
			if (role.getCode().equals(roleCode)) {
				return true;
			}
		}
		return false;
	}
}
